/********************************************************************************
 * Copyright (c) 2019 TypeFox and others
 *
 * This program and the accompanying materials are made available under the
 * terms of the Eclipse Public License v. 2.0 which is available at
 * http://www.eclipse.org/legal/epl-2.0.
 *
 * SPDX-License-Identifier: EPL-2.0
 ********************************************************************************/

import * as React from 'react';
import { withStyles, createStyles } from '@material-ui/styles';
import { Theme, WithStyles, Menu, Typography, MenuItem, IconButton } from '@material-ui/core';
import { Link } from 'react-router-dom';
import { isError } from '../../extension-registry-types';
import { MainContext } from '../../context';
import AccountBoxIcon from '@material-ui/icons/AccountBox';
import { createRoute } from '../../utils';
// import { useContext } from 'react';
// const { service } = useContext(MainContext);

export namespace UserLoginRoutes {
  export const OAUTH2 = createRoute(['oauth2', 'authorization']);
  export const GITHUB = createRoute([OAUTH2, 'github']);
  export const GITEE = createRoute([OAUTH2, 'gitee']);

  // export const GITEE = service.getLoginUrl();
}

const avatarStyle = (theme: Theme) => createStyles({
    avatar: {
        width: '30px',
        height: '30px'
    },
    link: {
        cursor: 'pointer',
        textDecoration: 'none'
    },
    menuItem: {
        cursor: 'auto'
    },
    menuButton: {
        border: 'none',
        background: 'none',
        padding: 0
    },
    logoutButton: {
        color: theme.palette.primary.dark,
    },
    icon: {
      width: '30px',
      height: '30px',
      verticalAlign: '-0.15em',
      fill: 'currentColor',
      overflow: 'hidden'
    }
});

class UserLoginComponent extends React.Component<UserLoginComponent.Props, UserLoginComponent.State> {

    static contextType = MainContext;
    declare context: MainContext;

    protected avatarButton: HTMLElement | null;
    protected abortController = new AbortController();

    constructor(props: UserLoginComponent.Props) {
        super(props);

        this.state = {
            open: false
        };
    }

    componentDidMount() {
    }

    componentWillUnmount() {
    }

    protected async updateCsrf() {
        try {
            const csrfToken = await this.context.service.getCsrfToken(this.abortController);
            if (!isError(csrfToken)) {
                this.setState({ csrf: csrfToken.value });
            }
        } catch (err) {
            this.context.handleError(err);
        }
    }

    protected readonly handleAvatarClick = () => {
        this.setState({ open: !this.state.open });
    };
    protected readonly handleClose = () => {
        this.setState({ open: false });
    };

    render(): React.ReactNode {
        {
          return <React.Fragment>
              <IconButton
                title={'Log in'}
                aria-label='Log in'
                onClick={this.handleAvatarClick}
                ref={ref => this.avatarButton = ref} >
                <AccountBoxIcon />
              </IconButton>

            <Menu
                open={this.state.open}
                anchorEl={this.avatarButton}
                transformOrigin={{ vertical: 'top', horizontal: 'right' }}
                onClose={this.handleClose}
            >
                <MenuItem className={this.props.classes.menuItem}>
                    <Link  onClick={this.handleClose} className={this.props.classes.link} to='/oauth2/authorization/gitee'>
                        <Typography variant='button' color='textPrimary' onClick={() => window.location.href = this.context.service.getLoginUrlGitee()}>
                        <svg className='icon' aria-hidden='true'>
                          <use xlinkHref='#icon-gitee'></use>
                        </svg> gitee
                        </Typography>
                    </Link>
                </MenuItem>
                <MenuItem className={this.props.classes.menuItem}>
                    <Link onClick={this.handleClose} className={this.props.classes.link} to='/oauth2/authorization/github'>
                        <Typography variant='button' color='textPrimary' onClick={() => window.location.href = this.context.service.getLoginUrl()}>
                            <svg className='icon' aria-hidden='true'>
                                <use xlinkHref='#icon-github'></use>
                            </svg> github
                        </Typography>
                    </Link>
                </MenuItem>
            </Menu>
          </React.Fragment>;
        }

    }
}

export namespace UserLoginComponent {
    export interface Props extends WithStyles<typeof avatarStyle> {
    }

    export interface State {
        open: boolean;
        csrf?: string;
    }
}

export const UserLogin = withStyles(avatarStyle)(UserLoginComponent);
